<template>
  <div style="padding:20px;">
    <el-input type="text" :value="currentValue" @change="handleChange">
      <el-button
        slot="suffix"
        size="small"
        type="success"
        @click="handleUp"
        :disabled="currentValue>=max"
      >增加</el-button>
      <el-button
        slot="suffix"
        size="small"
        type="success"
        @click="handleDown"
        :disabled="currentValue<=min"
      >减少</el-button>
    </el-input>
  </div>
</template>

<script>
export default {
  name: 'numberInputChild',
  props: {
    min: {
      type: Number,
      default: -Infinity //负无穷大
    },
    max: {
      type: Number,
      default: Infinity //正无穷大
    },
    value: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      currentValue: this.value
    }
  },
  wathch: {
    /* 实时监测当前输入的数字 */
    currentValue: function (val) {
      this.$emit('input', val) //触发父组件中v-model 进行双向数据绑定 
      //两个条件1：接受一个vlaue属性 2：有新的value时触发input事件
      // this.$emit('on-change', val)
    },
    /* 旧的value值 */
    value: function (val) {
      this.updateValue(val)
    }
  },
  mounted () {
    this.updateValue(this.value)
  },
  methods: {
    updateValue (val) {
      if (val > this.max) {
        val = this.max
      } else if (val < this.min) {
        val = this.min
      }
      this.currentValue = val
    },
    handleChange (event) {
      console.log(event)
      var val = event
      var max = max
      var min = min
      if (isValueNumber(val)) {
        val = Number(val)
        this.currentValue = val
        if (val > max) {
          this.currentValue = max
        } else if (val < min) {
          this.currentValue = min
        }
      } else {
        event = this.currentValue
      }
    },
    handleUp () {
      if (this.currentValue >= this.max) {
        return
      } else {
        this.currentValue += 1
      }
    },
    handleDown () {
      if (this.currentValue <= this.min) {
        return
      } else {
        this.currentValue -= 1
      }
    },
  }

}
function isValueNumber (value) {
  return (/^[+-]?(0|([1-9]\d*))(\.\d+)?$/).test(value + '')
}
</script>
